package com.lishu.carsafe.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.WindowManager;

import com.lishu.carsafe.R;
import com.lishu.carsafe.constant.UserPreferences;
import com.lishu.carsafe.model.entity.UserName;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.UserModel;
import com.lishu.carsafe.utils.StringUtil;


public class LauncherActivity extends BaseActivity {
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            gotoLogin();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_launcher);

        handler.sendEmptyMessageDelayed(0, 1500);
    }

    private void gotoLogin() {
        String name = UserPreferences.getInstance().getLoginName();
        String password = UserPreferences.getInstance().getLoginPassword();
        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(password)) {
            loginFail();
            return;
        }

        HttpLoader.login(name, password, new HttpLoader.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null || !model.success()) {
                    loginFail();
                    return;
                }

                UserModel.UserBean userBean = ((UserModel)model).getData();
                if (userBean == null) {
                    loginFail();
                    return;
                }
                UserName user = userBean.getUser();
                //保存返回的用户信息
                UserPreferences.getInstance().setUserId(user.getId());
                UserPreferences.getInstance().setLoginName(user.getLoginName());
                UserPreferences.getInstance().setUserName(user.getUserName());

                loginSuccess();
            }
        });
    }

    private void loginFail() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    private void loginSuccess() {
        startActivity(new Intent(LauncherActivity.this, MainActivity.class));
        finish();
    }
}
